package com.hskn.hss.filter;

import com.hskn.hss.core.exception.file.FileSizeLimitExceededException;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.ExcelReaderDataException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;

import javax.naming.SizeLimitExceededException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return AjaxResult.fail(message);
    }
    /**
     * 自定义导入数据异常处理
     */
    @ExceptionHandler(ExcelReaderDataException.class)
    public Object excelReaderDataExceptionHandler(ExcelReaderDataException e)
    {
        String message = e.getMessage();
        log.error(message, e);
        return AjaxResult.fail(message);
    }
    @ExceptionHandler(MultipartException.class)
    public AjaxResult exception(MaxUploadSizeExceededException e){
        if (e.getCause().getCause() instanceof FileSizeLimitExceededException){//单个文件大小超出限制抛出的异常
            log.error("message异常信息为=========》"+e.getMessage());
            log.error("cause异常信息为=========》"+e.getCause().getCause());
            return  AjaxResult.fail( "单个上传文件大小不能超过20MB");

        }else if (e.getCause().getCause() instanceof SizeLimitExceededException){//总文件大小超出限制抛出的异常
            log.error("message异常信息为=========》"+e.getMessage());
            log.error("cause异常信息为=========》"+e.getCause().getCause());
            return AjaxResult.fail( "总上传文件大小不能超过200MB");
        }
       return AjaxResult.fail("上传文件失败") ;
    }
}